using System.Linq;
using UnityEngine;

public class Object_NPC : MonoBehaviour,IInteractable,ISaveable
{
    [Header("Quest Details")]
    [SerializeField] private string npcTargetQuestId;
    [SerializeField] protected RewardType rewardNPC;
    [SerializeField] protected QuestDataSO[] questDatas;
    [Space]
    [Header("Dialogue")]
    [SerializeField] protected DialogueLineSO dialogueLine;
    [SerializeField] private Transform npc;
    [SerializeField] private GameObject interactToolTip;
    protected Player player;
    protected Animator npcAnim;
    protected UI uI;
    protected PlayerQuestManager questManager;
    private bool isFacingRight = true;

    [Header("-----InteractToolTip Floating-----")]
    [SerializeField] private float floatSpeed = 1;
    [SerializeField] private float floatRange = 0.2f;
    private Vector2 originalPosition;  //交互提示的初始位置

    protected virtual void Awake()
    {
        uI = FindAnyObjectByType<UI>();
        npcAnim = npc.GetComponent<Animator>();
        originalPosition = interactToolTip.transform.position;
        interactToolTip.SetActive(false);
        questManager = Player.Instance.questManager;

        questManager.OnFindHasQuest += GetAllQuest;
    }
    protected virtual void OnEnable()
    {
        
    }
    protected virtual void Update()
    {
        HandleFlip();
        HandleFloating();
    }


    public bool IsEnableInteractToolTip() => interactToolTip.activeSelf;
    private void HandleFlip()
    {
        if (player == null)
            return;
        float facingDir = player.transform.position.x - npc.position.x;

        if (facingDir < 0 && isFacingRight == true)
        {
            npc.Rotate(0, 180, 0);
            isFacingRight = false;
        }
        if (facingDir > 0 && isFacingRight == false)
        {
            npc.Rotate(0, 180, 0);
            isFacingRight = true;
        }
    }
    private void HandleFloating()
    {
        if (interactToolTip.activeSelf == false)
            return;
        
        float offset = Mathf.Sin(Time.time * floatSpeed) * floatRange;

        interactToolTip.transform.position = originalPosition + new Vector2(0, offset);
    }
    protected virtual void OnTriggerEnter2D(Collider2D collision)
    {
        Player player = collision.GetComponent<Player>();
        if (player == null)
            return;
        this.player = player;
        interactToolTip.SetActive(true);
    }

    protected virtual void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.TryGetComponent(out Player player))
        {
            interactToolTip.SetActive(false);
            this.player = null;
        }
    }
    //判断是否还有任务
    public QuestDataSO[] GetAllQuest() => questDatas;
    public virtual void Interact()
    {
        
    }

    public virtual void SaveData(ref GameData gameData)
    {
        
    }

    public virtual void LoadData(GameData gameData)
    {
        
    }
}
